package com.ruoyi.purchase.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.purchase.domain.*;
import com.ruoyi.purchase.helper.CompareObjectField;
import com.ruoyi.purchase.mapper.*;
import com.ruoyi.purchase.service.IPurchaseOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

/**
 * 订单Service业务层处理
 *
 * @author kevinness
 * @date 2025-01-02
 */
@Service
public class PurchaseOrderService implements IPurchaseOrderService
{
    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;

    @Autowired
    private ChangeDetailMapper changeDeatilMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private PurchasePlanMapper purchasePlanMapper;

    @Autowired
    private LogisticDetailMapper logisticDetailMapper;

    @Autowired
    private PlanOrderLinkMapper planOrderLinkMapper;

    /**
     * 查询订单
     *
     * @param orderNo 订单主键
     * @return 订单
     */
    @Override
    public PurchaseOrder selectPurchaseOrderByOrderNo(String orderNo)
    {
        return purchaseOrderMapper.selectPurchaseOrderByOrderNo(orderNo);
    }

    /**
     * 查询订单列表
     *
     * @param purchaseOrder 订单
     * @return 订单
     */
    @Override
    public List<PurchaseOrder> selectPurchaseOrderList(PurchaseOrder purchaseOrder)
    {
        return purchaseOrderMapper.selectPurchaseOrderList(purchaseOrder);
    }

    /**
     * 查询订单->只返回发货前的订单
     *
     * @param orderNo 订单主键
     * @return 订单
     */
    @Override
    public PurchaseOrder getPurchaseOrderByOrderNo(String orderNo)
    {
        return purchaseOrderMapper.getPurchaseOrderByOrderNo(orderNo);
    }

    /**
     * 采购执行查询订单列表
     *
     * @param purchaseOrder 订单
     * @return 订单集合
     */
    @Override
    public List<PurchaseOrder> getExecutionPurchaseOrderList(PurchaseOrder purchaseOrder){
        return purchaseOrderMapper.getExecutionPurchaseOrderList(purchaseOrder);
    }

    /**
     * 新增订单
     *
     * @param purchaseOrder 订单
     * @return 结果
     */
    @Override
    public int insertPurchaseOrder(PurchaseOrder purchaseOrder)
    {
        String username = SecurityUtils.getUsername();
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedNow = now.format(formatter);
        purchaseOrder.setOperator(username);
        purchaseOrder.setModifiedBy(username);
        purchaseOrder.setModifiedDate(formattedNow);
        return purchaseOrderMapper.insertPurchaseOrder(purchaseOrder);
    }

    /**
     * 修改订单,保存修改详情
     *
     * @param purchaseOrderParams 订单参数
     * @param operator 修改人身份
     * @return 结果
     */
    @Override
    public int updatePurchaseOrder(PurchaseOrderParams purchaseOrderParams, String operator)
    {
        PurchaseOrder purchaseOrder = new PurchaseOrder(purchaseOrderParams);
        List<OrderDetail> orderDetails = purchaseOrderParams.getDetails();

        //获取变更
        PurchaseOrder oldPurchaseOrder = purchaseOrderMapper
                .selectPurchaseOrderByOrderNo(purchaseOrder.getOrderNo());
        List<ChangeRecord> records = PurchaseOrder.comparePurchaseOrder(oldPurchaseOrder, purchaseOrder);
        for (OrderDetail orderDetail : orderDetails) {
            List<OrderDetail> oldDetails =
                    orderDetailMapper.selectOrderDetailList(orderDetail);
            records.addAll(OrderDetail.compareOrderDetail(oldDetails.get(0), orderDetail));
        }

        //json化
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = null;
        try {
            jsonString = objectMapper.writeValueAsString(records);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //获取修改人/时间信息
        String username = SecurityUtils.getUsername();
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedNow = now.format(formatter);
        purchaseOrder.setModifiedDate(formattedNow);
        purchaseOrder.setModifiedBy(username);

        ChangeDetail detail = new ChangeDetail(
                purchaseOrder,orderDetails,jsonString,username,
                operator, formattedNow, "待审核");
        return changeDeatilMapper.insertChangeDetail(detail);
    }

    /**
     * 修改订单，不保存详情
     *
     * @param purchaseOrderParams 订单参数
     * @return 结果
     */
    @Override
    public int updatePurchaseOrder(PurchaseOrderParams purchaseOrderParams){
        PurchaseOrder purchaseOrder = new PurchaseOrder(purchaseOrderParams);
        List<OrderDetail> orderDetails = purchaseOrderParams.getDetails();

        for (OrderDetail orderDetail : orderDetails) {
            List<OrderDetail> oldDetails =
                    orderDetailMapper.selectOrderDetailList(orderDetail);
            if(!Objects.equals(oldDetails.get(0).getQuantity(), orderDetail.getQuantity())){
                Double delta = orderDetail.getQuantity() - oldDetails.get(0).getQuantity();
                String planNo = planOrderLinkMapper.selectPlanNoByRawProductBatchNo(orderDetail.getRawProductBatch());
                PurchasePlan purchasePlan = purchasePlanMapper.selectPurchasePlanByPlanNo(planNo);
                purchasePlan.setPurchaseQuantity(purchasePlan.getPurchaseQuantity() + delta);
                purchasePlan.setPurchaseStatusByPurchaseQuantity();
                purchasePlanMapper.updatePurchasePlan(purchasePlan);
            }
        }

        //获取修改人/时间信息
        String username = SecurityUtils.getUsername();
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedNow = now.format(formatter);
        purchaseOrder.setModifiedDate(formattedNow);
        purchaseOrder.setModifiedBy(username);

        return purchaseOrderMapper.updatePurchaseOrder(purchaseOrder);
    }

    /**
     * 批量删除订单
     *
     * @param orderNos 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deletePurchaseOrderByOrderNos(String[] orderNos)
    {
        changeDeatilMapper.deleteChangeDetailByOrderNos(orderNos);
        orderDetailMapper.deleteOrderDetailByOrderNos(orderNos);
        return purchaseOrderMapper.deletePurchaseOrderByOrderNos(orderNos);
    }

    /**
     * 退货
     *
     * @param orderNo 订单编号
     * @return 结果
     */
    @Override
    public int returnPurchaseOrderByOrderNo(String orderNo){
        List<OrderDetail> orderDetails = orderDetailMapper.selectOrderDetailByOrderNo(orderNo);
        for (OrderDetail orderDetail : orderDetails) {
            String planNo = planOrderLinkMapper.selectPlanNoByRawProductBatchNo(orderDetail.getRawProductBatch());
            PurchasePlan purchasePlan = purchasePlanMapper.selectPurchasePlanByPlanNo(planNo);
            purchasePlan.setPurchaseQuantity(purchasePlan.getPurchaseQuantity() - orderDetail.getQuantity());
            purchasePlan.setPurchaseStatusByPurchaseQuantity();
            purchasePlanMapper.updatePurchasePlan(purchasePlan);
        }
        changeDeatilMapper.deleteChangeDetailByOrderNo(orderNo);
        orderDetailMapper.deleteOrderDetailByOrderNo(orderNo);
        return purchaseOrderMapper.deletePurchaseOrderByOrderNo(orderNo);
    }

    /**
     * 删除订单信息
     *
     * @param orderNo 订单主键
     * @return 结果
     */
    @Override
    public int deletePurchaseOrderByOrderNo(String orderNo)
    {
        return purchaseOrderMapper.deletePurchaseOrderByOrderNo(orderNo);
    }

    /**
     * 更新订单状态
     *
     * @param purchaseOrder 订单
     * @return 结果
     */
    @Override
    public int updatePurchaseOrderStatus(PurchaseOrder purchaseOrder){
        LogisticDetail logisticDetail = new LogisticDetail();
        //设置时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedNow = now.format(formatter);
        logisticDetail.setUpdateTime(formattedNow);
        logisticDetail.setOrderNo(purchaseOrder.getOrderNo());
        logisticDetail.setOrderStatus(purchaseOrder.getOrderStatus());
        //设置物流信息
        String status = purchaseOrder.getOrderStatus();
        if(Objects.equals(status, "已确认")){
            logisticDetail.setLogisticMessage("商家已确认，正在拣货中。");
        }
        else if(Objects.equals(status,"到出口港")){
            logisticDetail.setLogisticMessage("货品已运送到出口港，正在等待出港质检。");
        }
        else if(Objects.equals(status,"已发货")){
            logisticDetail.setLogisticMessage("订单已发货，可点击物流详情查看详细信息。");
        }
        else if(Objects.equals(status,"运送中")){
            logisticDetail.setLogisticMessage("货品正在运送中，可以通过地图关注实时位置。");
        }
        else if(Objects.equals(status,"已送达")){
            logisticDetail.setLogisticMessage("订单已送达港口，正在等待入港质检，请及时签收。");
        }
        else if(Objects.equals(status,"已签收")){
            logisticDetail.setLogisticMessage("订单已被签收。");
        }
        else if(Objects.equals(status,"调拨规划")){
            logisticDetail.setLogisticMessage("规划设计货品的调拨计划。");
        }
        else if(Objects.equals(status,"配送中")){
            logisticDetail.setLogisticMessage("货品配送中，可以点击配送明细查看调拨明细。");
        }
        else if(Objects.equals(status,"已入库")){
            logisticDetail.setLogisticMessage("货品已入库，订单结束。");
        }
        logisticDetailMapper.insertLogisticDetail(logisticDetail);
        return purchaseOrderMapper.updatePurchaseOrder(purchaseOrder);
    }
}